<!--
 * @Descripttion: 供应商注册
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-21 10:38
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-19 16:52:39
-->
<template>
  <div class="supplier-register">
    <div v-if="!formInfor">
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        
        <template >
          <el-row style="width:95%">
            <el-col :span="12">
              <el-form-item label="营业执照编码" prop="businessLicenseCode">
                <el-input placeholder="请输入" v-model="form.businessLicenseCode" maxlength="40"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="国别代码">
                <el-select v-model="form.countryCode" filterable placeholder="请选择">
                  <el-option
                    v-for="item in nationArr"
                    :key="item.publicCode"
                    :label="item.publicCodeName"
                    :value="item.publicCodeName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="orgNameZh" >
                <el-input placeholder="请输入" v-model="form.orgNameZh" maxlength="250"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中文简称">
                <el-input placeholder="请输入" v-model="form.orgNameZhShort" maxlength="100"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成立日期">
                <el-date-picker v-model="form.foundationDate" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业地址">
                <el-input placeholder="请输入" v-model="form.addr" maxlength="100"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮政编码" prop="zipCode">
                <el-input placeholder="请输入" v-model="form.zipCode" maxlength="20"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人手机号" prop="contactTel" >
                <el-input placeholder="请输入" v-model="form.contactTel" maxlength="11"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真号码" prop="fax">
                <el-input placeholder="请输入" v-model="form.fax" maxlength="20"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="mail">
                <el-input placeholder="请输入" v-model="form.mail" maxlength="40"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="网址" >
                <el-input placeholder="请输入" v-model="form.website" maxlength="40"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人代表" prop="legalPerson" >
                <el-input placeholder="请输入" v-model="form.legalPerson" maxlength="10"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人代表身份证/护照编码" prop="legalPersonId" >
                <el-input placeholder="请输入" v-model="form.legalPersonId" maxlength="32"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资本" prop="registeredCapital" >
                <el-input placeholder="请输入" v-model="form.registeredCapital" maxlength="32"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册地址" prop="registeredAddr" >
                <el-input placeholder="请输入" v-model="form.registeredAddr" maxlength="100"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业开始时间" prop="openStart">
                <el-date-picker v-model="form.openStart" type="date" placeholder="选择日期" :picker-options="pickerOptionsStart"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业结束时间" prop="openEnd">
                <el-date-picker v-model="form.openEnd" type="date" placeholder="选择日期" :picker-options="pickerOptions"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="bankName" >
                <el-input placeholder="请输入" v-model="form.bankName" maxlength="40"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行账号" prop="bankAccount" >
                <el-input placeholder="请输入" v-model="form.bankAccount" maxlength="40"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人姓名" prop="contact" >
                <el-input placeholder="请输入" v-model="form.contact" maxlength="10"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="width:95%">
            <el-form-item label="营业执照图片上传" prop="attachment1">
              <div class="set-flex">
                <el-upload
                    :action=fileUrl
                    :data="{ fileType: 18}"
                    :on-preview="handlePreview"
                    :on-remove="(file, fileList)=>handleRemove(file, fileList,0)"
                    :on-success="(res, file,fileList)=>handleAvatarSuccess(res, file,fileList,0)"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                    :headers=fileHeaders
                    multiple
                    :limit="1"
                    :on-exceed="handleExceed"
                    :file-list="permitFileList">
                  <el-button size="small" type="primary">选择附件</el-button>
                </el-upload>
                <p class="tips">可上传1张</p>
              </div>
              <el-input style="display: none;" v-model="form.attachment1"></el-input>
            </el-form-item>
          </el-row>
          <el-row style="width:95%">
            <el-form-item label="其他图片上传" prop="attachment2">
              <div class="set-flex">
                <el-upload
                    :action=fileUrl
                    :data="{ fileType: 18}"
                    :on-preview="handlePreview"
                    :on-remove="(file, fileList)=>handleRemove(file, fileList,1)"
                    :on-success="(res, file,fileList)=>handleAvatarSuccess(res, file,fileList,1)"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                    :headers=fileHeaders
                    multiple
                    :limit="1"
                    :on-exceed="handleExceed"
                    :file-list="otherFileList">
                  <el-button size="small" type="primary">选择附件</el-button>
                </el-upload>
                <p class="tips">可上传1张</p>
              </div>
              <el-input style="display: none;" v-model="form.attachment2"></el-input>
            </el-form-item>
          </el-row>
          <el-row style="width:95%">
            <el-form-item label="其他图片上传">
              <div class="set-flex">
                <el-upload
                  :action=fileUrl
                  :data="{ fileType: 18}"
                  :on-preview="handlePreview"
                  :on-remove="(file, fileList)=>handleRemove(file, fileList,2)"
                  :on-success="(res, file,fileList)=>handleAvatarSuccess(res, file,fileList,2)"
                  :on-error="handleAvatarError"
                  :before-upload="beforeAvatarUpload"
                  :headers=fileHeaders
                  multiple
                  :limit="1"
                  :on-exceed="handleExceed"
                  :file-list="otherFileList1">
                  <el-button size="small" type="primary">选择附件</el-button>
                </el-upload>
                <p class="tips">可上传1张</p>
              </div>
            </el-form-item>
          </el-row>
          <el-row class="submit" style="width:95%">
            <el-button type="primary" @click="onRegister">提交</el-button>
          </el-row>
        </template>
      </el-form>
    </div>
    <div v-else>
      <el-form ref="formInfor" label-width="180px" label-suffix=":" size="mini">
        <el-row class="infor" style="width:95%">
          <el-col :span="24">
            <p class="infor-title">供应商注册信息：</p>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客商编码">{{formInfor.orgCode}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称">{{formInfor.orgNameZh}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照编码">{{formInfor.businessLicenseCode}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国别代码">{{formInfor.countryCode}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中文简称">{{formInfor.orgNameZhShort}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成立日期">{{formInfor.foundationDate|sliceDate}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业地址">{{formInfor.addr}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮政编码">{{formInfor.zipCode}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人手机号">{{formInfor.contactTel}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传真号码">{{formInfor.fax}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱">{{formInfor.mail}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网址">{{formInfor.website}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人代表">{{formInfor.legalPerson}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人代表身份证/护照编码">{{formInfor.legalPersonId}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册资本">{{formInfor.registeredCapital}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业开始时间">{{formInfor.openStart|sliceDate}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业结束时间">{{formInfor.openEnd|sliceDate}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册地址">{{formInfor.registeredAddr}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行">{{formInfor.bankName}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行账号">{{formInfor.bankAccount}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名">{{formInfor.contact}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照图片">
              <!-- <img :src="formInfor.attachment1Url" class="preview" @click="previewImg(formInfor.attachment1Url)"> -->
              <common-img :id="formInfor.attachment1" :fileType="18" v-if="formInfor.attachment1"/>
              <span v-else>未上传</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他资源">
              <!-- <img :src="formInfor.attachment2Url" class="preview" @click="previewImg(formInfor.attachment2Url)"> -->
              <common-img :id="formInfor.attachment2" :fileType="18" v-if="formInfor.attachment2"/>
              <span v-else>未上传</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他资源">
              <!-- <img :src="formInfor.attachment3Url" class="preview" @click="previewImg(formInfor.attachment3Url)"> -->
              <common-img :id="formInfor.attachment3" :fileType="18" v-if="formInfor.attachment3"/>
              <span v-else>未上传</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核状态" style="color: orange">{{supplierStatusArr[status]}}</el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end" v-if="!formInfor.attachment1">
          <el-col :span="12" style="padding-left:180px">
              <common-add-img :dataList="addImgList" :options="addImgOptions"/>
          </el-col>
        </el-row>
      </el-form>
    </div>
  
    <!-- 查看附件   -->
    <el-dialog :visible.sync='dialogVisible'>
      <img width='100%' :src='dialogImageUrl' alt='' />
    </el-dialog>
  </div>
</template>

<script>
import { nation } from "@/assets/jsonDate/nation";
import {
  searchSupplierOrg,
  regSupplier,
  searchSupplierRegistered,
  searchSupplierRegisteredInfor,
  joinSupplier
} from "@/api/admin.api";
import tools from "@/tools";
import { deleteFile,getFileUrl} from '@/api/common.api'
import {checkPhone} from '@/validations/validate'
// 上传文件
import {beforeUpload} from '@/util/common'
// 上传文件
import fileUpdata from '@/api/file.config'
import commonImg from '@/views/admin/components/common-img'
import commonAddImg from '@/views/admin/components/common-add-img'
export default {
  name: "supplier-complete",
  components: {
    commonImg,
    commonAddImg
  },
  data() {
    // 传真号验证
    const validatFax = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (value) {
        const reg =  /^(\d{3,4}-)?\d{7,8}$/
        if (!reg.test(value)) {
          return callback(new Error("传真号码 '区号-传真号码'"))
        } else {
          return callback()
        }
      }
    }
    // 电子邮箱验证
    const validatEmail = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (value) {
        const reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
        if (!reg.test(value)) {
          return callback(new Error('电子邮箱格式不正确'))
        } else {
          return callback()
        }
      }
    }
    // 验证邮政编码
    const validatZipCode = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (value) {
        const reg = /^[0-8][0-7]\d{4}$/
        if (!reg.test(value)) {
          return callback(new Error('邮政编码格式不正确'))
        } else {
          return callback()
        }
      }
    }
    return {
      form: {
        orgNameZh: "",
        businessLicenseCode: "",
        countryCode: "中国",
        orgNameZhShort: "",
        foundationDate: "",
        addr: "",
        zipCode: "",
        contactTel: "",
        fax: "",
        mail: "",
        website: "",
        legalPerson: "",
        legalPersonId: "",
        registeredCapital: "",
        registeredAddr: "",
        openStart: "",
        openEnd: "",
        bankName: "",
        bankAccount: "",
        contact: "",
        // 图片id
        attachment1: "",
        attachment2: "",
        attachment3: '',
        userId: tools.localRead("userId"),
        
      },
      // 审核状态信息
      supplierStatusArr: ['申请正在审核中，请耐心等待～','审核已通过','审核已拒绝'],
      rules: {
        businessLicenseCode: [
          { required: true, message: "请输入营业执照编码", trigger: "blur" },
        ],
        orgNameZh: [
          { required: true, message: "请输入单位名称", trigger: "blur" },
        ],
        contactTel: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { validator: checkPhone, trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: "请输入法人代表", trigger: "blur" },
        ],
        legalPersonId: [
          {
            required: true,
            message: "请输入法人代表身份证/护照编码",
            trigger: "blur",
          },
        ],
        registeredCapital: [
          { required: true, message: "请输入注册资本", trigger: "blur" },
        ],
        registeredAddr: [
          { required: true, message: "请输入注册地址", trigger: "blur" },
        ],
        openStart: [
          { required: true, message: "请输入营业开始时间", trigger: "blur" },
        ],
        openEnd: [
          { required: true, message: "请输入营业结束时间", trigger: "blur" },
        ],
        bankName: [
          { required: true, message: "请输入开户行", trigger: "blur" },
        ],
        bankAccount: [
          { required: true, message: "请输入开户行账号", trigger: "blur" },
        ],
        contact: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
        ],
        attachment1: [
          { required: true, message: "请上传营业执照图片", trigger: "change" },
        ],
        fax:[
          { validator: validatFax, trigger: 'blur' }
        ],
        mail:[
          { validator: validatEmail, trigger: 'blur' }
        ],
        zipCode:[
          { validator: validatZipCode, trigger: 'blur' }
        ]
        // attachment2: [
        //   { required: true, message: "请上传其他资源", trigger: "change" },
        // ]
      },
      // 开始时间
      pickerOptionsStart: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
      },
      // 结束时间快捷方式
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now();
          },
          shortcuts: [{
            text: '无限期',
            onClick(picker) {
              picker.$emit('pick', new Date('2099/12/31 23:59:59'));
            }
          }],
      },
      // 是否显示注册表单
      showForm: false,
      // 国别
      nationArr: nation,
      // 附件
      fileHeaders: fileUpdata.headers(),
      fileUrl: fileUpdata.url,
      dialogVisible:false,
      dialogImageUrl:'',
      permitFileList:[],
      otherFileList: [],
      otherFileList1: [],
      // 基本信息
      formInfor: "",
      orgId: "",
      addImgList: [
        {
           name: '营业执照图片',
           key: 'attachment1',
           icon: 'iconshenfenzhengzhengmian',
           id: '',
           fileType: 18,
           required: true
         },
          {
            name:'其他资源',
           key: 'attachment2',
           icon: '',
           id: '',
           fileType: 18,
           required: false
         },
         {
          name:'其他资源',
           key: 'attachment3',
           icon: '',
           id: '',
           fileType: 18,
           required: false
         }
      ],
      addImgOptions: {type: 'supplier',orgid: ''}
    };
  },
  watch: {},
  computed: {},
  filters: {
    sliceDate(val){
      if(val && val.length>0){
        return val.slice(0,10)
      }
    }
  },
  created() {
    this.searchRegistered();
  },
  mounted() {},
  methods: {
    /**
     * @description 预览图片
     * @author 穆宏宇
     * @date 2020-10-26 11:03:18
     * @param
     * @return
     * */
    previewImg (imgUrl) {
      this.dialogImageUrl = imgUrl
      this.dialogVisible = true
    },
    /**
     * @description 查看文件信息
     * @author 穆宏宇
     * @date 2020-10-26 10:51:01
     * @param
     * @return
     * */
    getFileUrlFn (fileId,type){
      if (!fileId) return
      const arr = [
        {fileUrl:'attachment1Url'},
        {fileUrl:'attachment2Url'},
        {fileUrl:'attachment3Url'}
      ]
      getFileUrl(18,fileId).then(res=>{
        const key = arr[type].fileUrl
        this.formInfor[key]  = res
        this.$forceUpdate()
      })
    },
    /**
     * @description 注册-供应商
     * @author 穆宏宇
     * @date 2020-09-21 10:43:02
     * @param
     * @return
     * */
    onRegister() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          regSupplier(this.form)
            .then((res) => {
              this.$alert('提交成功！', '提示', {
                confirmButtonText: '确定',
                type: 'success',
                callback: action => {
                  this.searchRegistered();
                }
              })
            })
            .catch((err) => {});
        }
      });
    },
    // 查询是否注册过
    searchRegistered() {
      const id = this.$tools.localRead('userId')
      searchSupplierRegistered(id).then((res) => {
        if (res&&res[0]) {
          this.status = res[0].auditStatus
          this.orgId = res[0].orgId
          this.addImgOptions.orgId = this.orgId
          searchSupplierRegisteredInfor(this.orgId).then((resDate) => {
            if (resDate && resDate.id) {
              if (this.status==2) {
                this.showForm = true
                this.form = resDate
                this.form.userId = tools.localRead("userId")
                this.$alert("审核未通过，请修改信息后，再次提交！", "提示", {
                  confirmButtonText: "确定",
                })
              }else{
                this.formInfor = resDate
                this.$forceUpdate()
                // 获取营业执照图片url
                this.getFileUrlFn(this.formInfor.attachment1, 0)
                // 获取其他资源图片url
                this.getFileUrlFn(this.formInfor.attachment2, 1)
                // 获取其他资源图片url
                this.getFileUrlFn(this.formInfor.attachment3, 2)
                
              }
            }
          })
        }
      })
    },
    // 查询组织注册信息
    // 查询组织
    queryOrg() {
      if (this.form.orgNameZh) {
        searchSupplierOrg(this.form.orgNameZh)
          .then((res) => {
            // console.log(res);
            this.showForm = false;
            // this.$confirm("查询组织成功，确定加入此组织吗？", "提示", {
            //   confirmButtonText: "确定",
            //   cancelButtonText: "取消",
            //   type: "success",
            // })
            //   .then(() => {
            //     if (res&&res[0]) {
            //       this.joinSupplierFn(res[0].id)
            //     }
            //   })
            //   .catch(() => {});
          this.$alert('此供应商已注册，请联系供应商管理员加入该供应商。', '提示', {
            confirmButtonText: '确定'
          })

          })
          .catch((err) => {
            if (err.code == -2) {
              this.showForm = true;
            }
          });
      } else {
        // this.$message.error("请输入先组织机构!");
      }
    },
    // 加入组织
    joinSupplierFn(){
      joinSupplier({userId:this.$tools.localRead('userId')}).then(res=>{
        this.$alert('提交成功！', '提示', {
          confirmButtonText: '确定'
        })
      })
    },
    // 预览附件
    handlePreview (file) {
      getFileUrl(file.fileType,file.id).then(res=>{
        this.dialogImageUrl = res
        this.dialogVisible = true
      })
    },
    // 删除附件
    handleRemove (file, fileList,type) {
      console.log('删除')
      if (file && file.status === "success") {
        const arr = [
          {fileList:this.permitFileList, fileId:'attachment1'},
          {fileList:this.otherFileList, fileId:'attachment2'},
          {fileList:this.otherFileList1, fileId:'attachment3'}
        ]
        arr[type].fileList= fileList
        const key = arr[type].fileId
        this.form[key] = ''
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多只可上传一个附件，您已超限！");
      // this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleAvatarSuccess(res, file,fileList,type) {
      const arr = [
        {fileList:this.permitFileList, fileId:'attachment1'},
        {fileList:this.otherFileList, fileId:'attachment2'},
        {fileList:this.otherFileList1, fileId:'attachment3'}
      ]
      arr[type].fileList= fileList
      const key = arr[type].fileId
      this.form[key] = res.data.id
    },
    handleAvatarError(res, file) {
      this.$message.error("文件上传失败，请重试")
    },
    beforeAvatarUpload(file) {
      //const isJPG = file.type === 'image/jpeg';
      const typeList = ['png', 'jpg','jpeg']
      const isJPG = beforeUpload(file,typeList)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传文件格式不符合!')
      }
      if (!isLt5M) {
        this.$message.error('上传身份证图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
  },
};
</script>

<style scoped lang="scss">
.supplier-register {
  // padding: 20px 10px;
  background: #fff;
  
  // overflow-y: scroll;
  // height: 100%;
  .el-select,
  .el-input {
    width: 100%;
  }
  // 提示消息
  .org-msg {
    font-size: 12px;
    padding: 20px 180px;
    color: $--color-danger;
  }
  // 提示文字
  .tips {
    font-size: 12px;
    padding-left: 20px;
    color: $--color-danger;
  }
  // 提交按钮
  .submit {
    margin-top: 20px;
    text-align: center;
    .el-button {
      padding: 12px 40px;
    }
  }
  // 内容
  .infor{
    max-width:1000px;
    margin: 0 auto;
  }
  // 显示详情title
  .infor-title{
    font-size: 18px;
    padding: 20px ;
    font-weight: bold;
  }
  .preview {
    width: 80px;
    height: 80px;
    cursor: pointer;
  }
}
</style>
